<?php
/*
  +----------------------------------------------------------------------+
  | UCModActiveUser.php                                                          |
  +----------------------------------------------------------------------+
  | Copyright (c) 2010 snda.com - Web Development Center                 |
  +----------------------------------------------------------------------+
  | UCModaddActiveUser engine                                                      |
  +----------------------------------------------------------------------+
  | Authors: Terry <leo9127@163.com>                                     |
  +----------------------------------------------------------------------+
*/

require_once(dirname(__FILE__).'/../../libraries/UCLibCache.php');
require_once(dirname(__FILE__).'/../../config/comment/UCConfComment.php');
require_once(dirname(__FILE__).'/../../libraries/UCLibPDOFactory.php');
require_once(dirname(__FILE__).'/../../models/user/UCModUserInfo.php');
require_once(dirname(__FILE__).'/../../models/medal/UCModMedalInterface.php');

class UCModActiveUser{
	
	//生成KEY
	static function _keyActiveUser($sex='all',$type=''){
		//$user_id = strtolower(trim($user_id));
		if(empty($type)){
			$key = md5("getActiveUser_News_List_".$sex);
		}elseif($type == 'total'){
			$key = md5("getActiveUser_News_Total_".$sex);
		}else{
			return false;
		}
		return $key;
	}
	
	//将活跃用户的数据写入DB并更新CACHE
	static function writeActiveUser($file,$sub_user=''){
		//检查文件是否存在
		if(!file_exists($file)){
			return false;
		}
		$handle = fopen($file, "rb");
		while(!feof($handle)){
			$buffer = fgets($handle, 1024);
			$buffer = explode("#", $buffer);
			$user_id = strtolower(trim($buffer[0]));
			//获取用户性别
			$user = UCModUserInfo::getUser($user_id);
			$data = $user->getAttributes(array(USERINFO_GENDER_DESC));
			$sex = $data[USERINFO_GENDER_DESC];
			$channel = $buffer[1];
			//判断用户是否合法
			$info = UCModUserInfo::isUCUser($user_id);
			if($info == 0 || $info == false){
				continue;
			}
			//检查用户是否存在
			if(self::whetherActiveUser($user_id)){
				continue;
			}
			$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
			$data = array('user_id'=>$user_id,'sex'=>$sex,'channel'=>$channel,'sub_time'=>date("Y-m-d H:i:s"),'sub_user'=>$sub_user);
			$pdo->insert($data);
			//修改用户性别的CACHE数据
			$key = self::_keyActiveUser($sex);
			$cache = new UCLibCache('activeuser');
			$row = $cache->read($key);
			if($row === false){
				$row = array();
			}
			if(!empty($channel)){
				$channel = explode(",",$channel);
			}
			$row[] = array('user_id'=>$user_id,'sex'=>$sex,'channel'=>$channel);
			$cache->write($key,$row);
			//将用户性别总数加1
			$key = self::_keyActiveUser($sex,'total');
			$row = $cache->read($key);
			if($row === false || $row <=0){
				$row = 1;
			}else{
				$row = $row+1;
			}
			$cache->write($key,$row);
			//修改全部的数据
			$key = self::_keyActiveUser('all');
			$row = $cache->read($key);
			if($row === false){
				$row = array();
			}
			if(!empty($channel)){
				$channel = explode(",",$channel);
			}
			$row[] = array('user_id'=>$user_id,'sex'=>$sex,'channel'=>$channel);
			$cache->write($key,$row);
			//将全部的总数加1
			$key = self::_keyActiveUser('all','total');
			$row = $cache->read($key);
			if($row === false || $row <=0){
				$row = 1;
			}else{
				$row = $row+1;
			}
			$cache->write($key,$row);
			$cache->close();
		}
		fclose($handle);
	}
	
	//添加单个用户
	static function writeOneUser($user_id,$channel='',$sub_user=''){
		if(empty($user_id)){
			return false;
		}
		$user_id = strtolower(trim($user_id));
		//判断用户是否合法
		$info = UCModUserInfo::isUCUser($user_id);
		if($info == 0 || $info == false){
			return "001";
		}
		//检查用户是否存在
		if(self::whetherActiveUser($user_id)){
			return "002";
		}
		//获取用户性别
		$user = UCModUserInfo::getUser($user_id);
		$data = $user->getAttributes(array(USERINFO_GENDER_DESC));
		$sex = $data[USERINFO_GENDER_DESC];
		if(empty($sex)){
			$sex = '女';
		}
		$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
		$data = array('user_id'=>$user_id,'sex'=>$sex,'channel'=>$channel,'sub_time'=>date("Y-m-d H:i:s"),'sub_user'=>$sub_user);
		if(!$pdo->insert($data)){
			return '003';
		}
		//增加帮帮糖勋章
		UCModMedalInterface::addUserMedal($user_id, UCConfMedal::MEDAL_LIMIT_BANGBANGTANG);
		$cache = new UCLibCache('activeuser');
		//清空总数CACHE
		$key = self::_keyActiveUser('all');
		$cache->delete($key);
		$key = self::_keyActiveUser('all','total');
		$cache->delete($key);
		//依据性别清CACHE
		$key = self::_keyActiveUser($sex);
		$cache->delete($key);
		$key = self::_keyActiveUser($sex,'total');
		$cache->delete($key);
		$cache->close();
		return true;
	}
	
	//修改用户数据
	static function reviseActiveUser($user_id,$channel=''){
		$user_id = strtolower(trim($user_id));
		//检查用户是否存在
		if(!self::whetherActiveUser($user_id)){
			return '001';
		}
		$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
		if(!$pdo->update(array('channel'=>$channel),array('user_id'=>$user_id))){
			return '002';
		}
		$userinfo = self::getOneActiveUser($user_id);
		$sex = $userinfo['sex'];
		$cache = new UCLibCache('activeuser');
		//清空总数CACHE
		$key = self::_keyActiveUser('all');
		$cache->delete($key);
		$key = self::_keyActiveUser('all','total');
		$cache->delete($key);
		//依据性别清CACHE
		$key = self::_keyActiveUser($sex);
		$cache->delete($key);
		$key = self::_keyActiveUser($sex,'total');
		$cache->delete($key);
		$cache->close();
		return true;		
	}
	
	//读取单个用户数据
	static function getOneActiveUser($user_id){
		$row = self::getAllUser();
		if($row === false){
			return false;
		}
		foreach($row as $key=>$val){
			if($val['user_id'] == $user_id){
				return $val;
			}
		}
		return false;
	}
	
	//判断是否是活跃用户 是返回true 否返回false
	static function whetherActiveUser($user_id){
		$user_id = strtolower(trim($user_id));
		$row = self::getOneActiveUser($user_id);
		if($row === false){
			return false;
		}else{
			return true;
		}
	}
	
	//依据传入的条件读取用户数据
	static function getAllUser($sex='all'){
		$cache = new UCLibCache('activeuser');
		$key = self::_keyActiveUser($sex);
		$row = $cache->read($key);
		if($row === false && $row != 'error'){
			$data = array();
			$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
			if($sex=='all'){
				$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user_id<>'' ORDER BY sub_time DESC";
			}else{
				$sql = "SELECT * FROM $pdo->database.$pdo->table WHERE user_id<>'' and sex=? ORDER BY sub_time DESC";
				$data[] = $sex;
			}
			$ret = $pdo->query_with_prepare($sql,$data);
			if($ret === false || !is_array($ret)){
  			$cache->write($key,'error',1800);
  			$cache->close();
  			return 'error';
  		}
  		foreach($ret as $keys=>$val){
  			if(!empty($val['channel'])){
  				$ret[$keys]['channel'] = explode(",",$val['channel']);
  			}else{
  				$ret[$keys]['channel'] = array();
  			}
  		}
  		$row = $ret;
  		$cache->write($key,$row);
  		$cache->close();
  	}
  	if($row == 'error'){
  		$row = false;
  	}
  	return $row;
  }
	
	//读取活跃用户数据
	static function getActiveUser($sex='all',$stat=0,$page_size=20){
		//读取总数
		$total = self::getActiveUserNum($sex);
		if($total == 0){
			return array('total'=>0,'rows'=>array());
		}
		if($total <= $stat || $total <= ($stat+$page_size)){
			$stat = $total-$page_size;
		}
		if($stat < 0){
			$stat == 0;
		}
		if($page_size > ($total-$stat)){
			$page_size = ($total-$stat);
		}
		$row = self::getAllUser($sex);
		if($row === false || $row == 'error'){
			return array('total'=>0,'rows'=>array());
		}
		$export = array();
		for($i=$stat;$i<($stat+$page_size);$i++){
			if(!empty($row[$i]['user_id'])){
				$export[] = $row[$i];
			}
		}
		return array('total'=>$total,'rows'=>$export);
	}
	
	//读取活跃用户总数
	static function getActiveUserNum($sex='all'){
		$key = self::_keyActiveUser($sex,'total');
		$cache = new UCLibCache('activeuser');
		$total = $cache->read($key);
		if($total === false && $total != 'error'){
			$data = array();
			$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
			if($sex=='all'){
				$sql = "SELECT count(*) as total FROM $pdo->database.$pdo->table WHERE user_id<>'' ORDER BY sub_time DESC";
			}else{
				$sql = "SELECT count(*) as total FROM $pdo->database.$pdo->table WHERE user_id<>'' and sex=? ORDER BY sub_time DESC";
				$data[] = $sex;
			}
			$ret = $pdo->query_one_row_with_prepare($sql,$data);
			if(!$ret){
				$cache->write($key,'error',1800);
  			$cache->close();
  			return '0';
  		}
  		$total = $ret['total'];
  		$cache->write($key,$total);
  	}
  	if($total == 'error'){
  		$total = 0;
  	}
  	return $total;
  }
	
	//随机读取活跃用户数据
	static function getRandomActiveUser($sex='all',$page_size=20){
		//读取总数
		$total = self::getActiveUserNum($sex);
		if($total == 0){
			return array('total'=>0,'rows'=>array());
		}
		if($total <= $page_size){
			$page_size = $total;
		}
		$row = self::getAllUser($sex);
		if($row === false || $row == 'error'){
			return array('total'=>0,'rows'=>array());
		}
   if($page_size>0)$rows = array_chunk($row, $page_size);
		if(count($rows[count($rows)-1]) < $page_size && ($total/$page_size) > 1){
			$listnum = ($page_size-count($rows[(count($rows)-1)]));
			if($listnum > 0){
				for($i=0;$i<$listnum;$i++){
					$rows[(count($rows)-1)][] = $row[$i];
				}
			}
		}
		$getNum = rand(0,(count($rows)-1));
		return array('total'=>$total,'rows'=>$rows[$getNum]);
	}
	
	/***********************
	* 依据频道号随机读取一批用户
	* $channel = all 全部
	* $channel = twitter 推他
	* $channel = apps 小应用
	* $channel = friends 好友
	* $channel = candy 糖果奇缘
	* $sex 性别 all 全部/男/女
	* $page_size=20 每次读取多少行
	*****************************/
	static function getChannelActiveUser($channel='all',$sex='all',$page_size=20){
		$ch = array('all','twitter','friends','apps','candy');
		if(!in_array($channel,$ch)){
			return false;
		}
		if($channel == 'all'){
			$row = self::getRandomActiveUser($sex,$page_size);
			return $row;
		}
		//读取总数
		$total = self::getActiveUserNum($sex);
		if($total == 0){
			return array('total'=>0,'rows'=>array());
		}
		$row = self::getAllUser($sex);
		if($row === false || $row == 'error'){
			return array('total'=>0,'rows'=>array());
		}
		$new = array();
		if($channel == 'friends'){
			foreach($row as $key=>$val){
				if(in_array($channel,$val['channel'])) $new[] = $val;
			}
		}else{
			foreach($row as $key=>$val){
				if(in_array($channel,$val['channel']) || count($val['channel']) == 0 || in_array('all',$val['channel'])) $new[] = $val;
			}
		}
		$total = count($new);
		if($total == 0){
			return array('total'=>0,'rows'=>array());
		}
		if($page_size>0)$rows = array_chunk($new, $page_size);
		if(count($rows[count($rows)-1]) < $page_size && ($total/$page_size) > 1){
			$listnum = ($page_size-count($rows[(count($rows)-1)]));
			if($listnum > 0){
				for($i=0;$i<$listnum;$i++){
					$rows[(count($rows)-1)][] = $new[$i];
				}
			}
		}
		$getNum = rand(0,(count($rows)-1));
		return array('total'=>$total,'rows'=>$rows[$getNum]);
	}
	
	//删除活跃用户
	static function delActiveUser($user_id){
		$user_id = strtolower(trim($user_id));
		if(!self::whetherActiveUser($user_id)){
			return false;
		}
		//读取用户信息
		$userInfo = self::getOneActiveUser($user_id);
		$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
		$sql = "DELETE FROM $pdo->database.$pdo->table WHERE user_id=?";
		$data = array($user_id);
		$row = $pdo->exec_with_prepare($sql,$data);
		//删除棒棒糖勋章
		UCModMedalInterface::delUserMedal($user_id, UCConfMedal::MEDAL_LIMIT_BANGBANGTANG);
		$cache = new UCLibCache('activeuser');
		//清空总数CACHE
		$key = self::_keyActiveUser('all');
		$cache->delete($key);
		$key = self::_keyActiveUser('all','total');
		$cache->delete($key);
		//依据性别清CACHE
		$key = self::_keyActiveUser($userInfo['sex']);
		$cache->delete($key);
		$key = self::_keyActiveUser($userInfo['sex'],'total');
		$cache->delete($key);
		$cache->close();
		return true;
	}
	
	//直接读取DB返回数据
	static function dbselectUser($user_id='',$sex='',$channel=array(),$stat=0,$page_size=20){
		$pdo = UCLibPDOFactory::getPDO('activeuser','','commentdbconfig');
		$where = '';
		$data = array();
		if(!empty($user_id) || !empty($sex) || !empty($channel)){
			$wherearr = array();
		}
		if(!empty($user_id)){
			$wherearr[] = "user_id LIKE '%".$user_id."%'";
		}
		if(!empty($sex)){
			$wherearr[] = 'sex=?';
			$data[] = $sex;
		}
		if(!empty($channel) && count($channel)>0 && is_array($channel)){
			$chwhere = array();
			foreach($channel as $chk=>$chv){
				$chwhere[] = " channel LIKE '%".$chv."%'";
			}
			$chinfo = implode(" or ", $chwhere);
			$wherearr[] = ' ('.$chinfo.')';
		}
		if(is_array($wherearr) && count($wherearr)>0){
			$where = " WHERE ".implode(" and ", $wherearr);
		}
		//读取数量
		$sql = "SELECT count(*) as total FROM $pdo->database.$pdo->table".$where;
		$ret = $pdo->query_one_row_with_prepare($sql,$data);
		if(!$ret){
  		return '0';
  	}
  	$total = $ret['total'];
  	/*if($total <= $stat){
			$stat = $total-$page_size;
		}*/
		$data[] = $stat;
		$data[] = $page_size;
		$sql = "SELECT * FROM $pdo->database.$pdo->table".$where." ORDER BY sub_time DESC LIMIT ?,?";
		$ret = $pdo->query_with_prepare($sql,$data);
		if($ret === false || !is_array($ret)){
  		return false;
  	}
  	return array('total'=>$total,'rows'=>$ret);
	}
}